package com.pignest.hotel.service;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;



import com.pignest.framework.util.Utils;
import com.pignest.hotel.beans.Card;
import com.pignest.hotel.beans.IntegralLog;
import com.pignest.hotel.beans.Member;
import com.pignest.hotel.beans.MemberPrice;
import com.pignest.hotel.beans.Memberchargehistrory;
import com.pignest.hotel.beans.RoomType;
import com.pignest.hotel.dao.MemberDao;
import com.pignest.hotel.definition.ChargeOpType;
import com.pignest.hotel.definition.MemberState;
import com.pignest.hotel.definition.PayMethod;
import com.pignest.hotel.spring.Services;
import com.pignest.hotel.system.Hotel;
import com.pignest.hotel.util.MoneyUtil;
import com.pignest.hotel.beans.MemberLevel;
public class MemberService extends BaseService{
	
    private MemberDao memberDao;
    
	public void setMemberDao(MemberDao memberDao) {
		this.memberDao = memberDao;
	}
	public Member getMember(String id){
		return memberDao.get(Member.class, id);
	}
	public List<Member> listAllMember(){
	    	
	    return memberDao.listAll(Member.class);
	}
	public void addMember(Member member){
    	
		   memberDao.insert(member);
		    	
		}
	public void addMember(Member member,String cardSerialno){
	    	
	   memberDao.insert(member);
	   if(cardSerialno!=null)
	     Services.getCardService().grantCard(cardSerialno, member);
	    	
	}
	public void updateMember(Member member)
	{
		memberDao.update(member);
	}
	public void updateMember(Member member,String cardSerialno){
	    	
	    	memberDao.update(member);
	    	if(cardSerialno!=null)
	   	     Services.getCardService().grantCard(cardSerialno, member);
	    	
	    }
	public List<Member> query( String name,  String mobile, List<String> sex, List<String> type, String mail, String cardNo){
		return memberDao.query(name, mobile, sex, type, mail, cardNo);
	}
	
	public void deleteMembers(String ids[]){
		if(ids==null)
			return ;
		for(int i=0;i<ids.length;i++){
			deleteMember(ids[i]);
		}
	}
	public void deleteMember(String id){
		memberDao.delete(Member.class, id);
	}
	public List<Member> QueryBy(String hql,int start,int length){
		return memberDao.getListForPage(hql, start, length);
	}
	public List<Member> queryByPage(String name,String mobile,int start,int length)
	{
		StringBuffer hql = new StringBuffer();
		hql.append(" from Member m where 1=1 ");
		if(name!=null&&!name.equals(""))
		{
			hql.append(" and m.name like '%").append(name).append("%'");
		}
		if(mobile!=null&&!mobile.equals(""))
		{
			hql.append(" and m.mobile like '%").append(mobile).append("%'");
		}
		return QueryBy(hql.toString(),start,length);
		
	}
	
	public List<Member> listMembers(String name, String cardNo, String phone) {
		return memberDao.listMembers(name, cardNo, phone, 20, 0);
	}
	
	public Member getMemberByCardNumber(String cardNumber) {
		return get(Member.class, "cardNo", cardNumber);
	}
	
	/**查询所有会员级别
	 * 
	 * ***/
	public List<MemberLevel> QueryMemberLevel(){
		
		return memberDao.listAll(MemberLevel.class);
	}
	public void addMemberLevel(MemberLevel level){
		 memberDao.insert(level);
	}
	public void updateMemberLevel(MemberLevel level){
		memberDao.update(level);
	}
	/**
	 * levelname :等级名称
	 * classid:  null 为新增时的验证
	 *           否则是修改时的验证
	 * **/
	public boolean isExistMemberLevel(String levelname,String classid){
		String hql="from MemberLevel where memberlevel='"+levelname+"'";
		if(classid!=null){
			hql=hql+" and id !='"+classid+"'";
		}
		List list =memberDao.find(hql);
		return list != null && !list.isEmpty();
	}
	public MemberLevel getMemberLevel(String classid){
		return memberDao.get(MemberLevel.class, classid);
	}
	public void deleteMemberLevel(MemberLevel level){
		memberDao.delete(level);
	}
	public String memberLevelDelete(String classId){
		//先查询父表是否有记录
		String hql="from MemberPrice t where t.memberLevel.id='"+classId+"'";
		List list =memberDao.find(hql);
		if(list!=null&&list.size()>0)
			return "会员价格有该等级的引用不能删除!";
		else{
			MemberLevel level=memberDao.get(MemberLevel.class, classId);
			deleteMemberLevel(level);
			return "";
		}
	}
	
	//*********增加会员房价*************************************
	
	public List<MemberPrice> findMemberPrice(String hql){
		return memberDao.find(hql);
	}
	public RoomType getRoomType(String id){
		return memberDao.get(RoomType.class, id);
	}

	public void addMemberPrice(MemberPrice price){
		memberDao.insert(price);
		
	}
	public void deleteAllMemberPrice()
	{
		List <MemberPrice>list =memberDao.find(" from MemberPrice");
		for(MemberPrice mp :list){
			memberDao.delete(mp);
		}
		
	}
	//***修改会员房价
	public void updateMemberPrice(MemberPrice price){
		memberDao.update(price);
	}
	public List<MemberLevel> queryMemberLevelList(){
		return memberDao.listAll(MemberLevel.class);
	}
	public List<RoomType> queryRoomTypeList(){
		return memberDao.listAll(RoomType.class);
	}

	public MemberPrice getMemberPriceId(String id) {
		return memberDao.get(MemberPrice.class, id);
	}

	public void initMemberPrices() {
		List<MemberPrice> current = queryMemberPriceList();
		List<RoomType> rtList = queryRoomTypeList();
		List<MemberLevel> levelList = queryMemberLevelList();
		deleteAllMemberPrice();
		for (RoomType rt : rtList) {
			for (MemberLevel l : levelList) {
				MemberPrice nP = getMemberPrice(l, rt, current);
				if (nP == null) {
					nP = new MemberPrice();
					nP.setMemberLevel(l);
					nP.setRoomType(rt);
					nP.setPrice(rt.getPrice());
				} else {
					MemberPrice p = new MemberPrice();
					p.setMemberLevel(l);
					p.setRoomType(rt);
					p.setPrice(nP.getPrice());
					nP = p;
				}
				addMemberPrice(nP);
			}
		}
	}

	private MemberPrice getMemberPrice(MemberLevel l, RoomType r, List<MemberPrice> mpList) {
		for (MemberPrice mp : mpList) {
			if (StringUtils.equals(mp.getMemberLevel().getId(), l.getId()) && StringUtils.equals(mp.getRoomType().getId(), r.getId())) {
				return mp;
			}
		}
		return null;
	}
	
	//判断会员房价是否同时存在两种类型
	//会员房价的定义是：同一会员等级同一房间类型只能定一个价格
	public String isOnlyTwoType(String levelId,String roomTypeId,String id){
		String hql="from MemberPrice t where t.memberLevel.id='"+levelId+"' and t.roomType.id='"+roomTypeId+"'";
        if(id!=null){
        	hql =hql+" and  t.id!='"+id+"'";
        }
		List<MemberPrice> list =memberDao.find(hql);
		if(list!=null&&list.size()>0){
			MemberPrice price =list.get(0);
			String levelName =price.getMemberLevel().getMemberlevel();
			String roomtypename=price.getRoomType().getName();
			return "当前已经存在等级："+levelName+"与房间类型："+roomtypename+"的价格!请重新确认";
		}else{
			return "";
		}
	}
	public String deleteMemberPrices(String ids[]){
		if(ids==null)
			return "没有选择!";
		for(int i=0;i<ids.length;i++){
			deleteMemberPrice(ids[i]);
		}
		return "";
	}
	public void deleteMemberPrice(String id){
		memberDao.delete(MemberPrice.class, id);
	}
	public List<MemberPrice> queryMemberPriceList(){
		return memberDao.find(" from MemberPrice");
	}
	//**************************************************
	/**
	 * 根据会员ID与房间类型获得会员房价
	 * 
	 * ****/
	public int getMemberPrice(String memberId,String roomTypeId){
		Member member =this.getMember(memberId);
		StringBuffer hql = new StringBuffer();
		if(member!=null){
			hql.append(" from MemberPrice b where b.memberLevel.id='"+member.getMemberLevel().getId()+"'");
			hql.append(" and b.roomType.id='"+roomTypeId+"'");
		    List<MemberPrice> ps=memberDao.find(hql.toString());
		    if(ps!=null&&ps.size()!=0){
		    	MemberPrice p=ps.get(0);
		    	return p.getPrice();
		    }
		}
		return 0;
	}
	/***
	 * 验证手机号、证件号、与邮件是否有重复
	 * ***/
    public String ExistMember(Member member){
    	try{
    		String rStr="";
    		if(member==null)
    			return "输入会员无效！出现null";
    	    StringBuffer hql = new StringBuffer();
    	    hql.append(" from Member where 1=1 ");
    	    String or="";
    	    if((member.getMobile()!=null&&!member.getMobile().equals(""))||
    	    		(member.getMail()!=null&&!member.getMail().equals(""))||
    	    		(member.getCertificateNo()!=null&&!member.getCertificateNo().equals(""))){
    	    	or="(";
    	    }
    	    if(member.getMobile()!=null&&!member.getMobile().equals("")){
    	    	or=or+ " or mobile ='"+member.getMobile()+"'";
    	    }
    	    if(member.getMail()!=null&&!member.getMail().equals("")){
    	    	or=or+" or mail='"+member.getMail()+"'";
    	    }
    	    if(member.getCertificateNo()!=null&&!member.getCertificateNo().equals("")){
    	    	or=or+" or certificateNo='"+member.getCertificateNo()+"'";
    	    }
    	    if((member.getMobile()!=null&&!member.getMobile().equals(""))||
    	    		(member.getMail()!=null&&!member.getMail().equals(""))||
    	    		(member.getCertificateNo()!=null&&!member.getCertificateNo().equals(""))){
    	    	or=or+")";
    	    }
   
    	    if(or.length()!=0){
    	    	or=or.replaceFirst("or", "");
    	    }
    	    if(member.getId()!=null){
    	    	hql.append(" and id!='"+member.getId()+"'");
    	    }
    	    if(or!=""){
    	    	hql.append(" and "+or);
    	    }
    	    
    	    List list =this.find(hql.toString());
    	    if(list.size()==0){
    	    	rStr="";
    	    }else{
    	    	rStr="有存在手机、证件号、邮件";
    	    }
    	    return rStr;
    	}catch(Exception e){
    		e.printStackTrace();
    		return e.getMessage();
    	}
    }
    /**
     * 根据会员的单个数据项进行验证是否存在
     * ***/
    public String ExistMemberSingle(String col,String value,String colcn,String id){
    	try{
    		String rStr="";
    		StringBuffer hql = new StringBuffer();
    		hql.append(" from Member where 1=1 ");
    		if(col==null||col.equals("")){
    			return "无效的字段名";
    		}
          
    		if(value!=null&&!value.equals("")){
    			hql.append(" and "+col+"='"+value+"'");
    		}
    		if(id!=null&&!id.equals("")){
    			hql.append(" and id!='"+id+"'");
    		}
    		if(value.equals("")){
    			return "无效为空";//
    		}else{
    			List list =this.find(hql.toString());
    			if(list.size()>0){
    		       rStr="已存在"+colcn+":"+value;
    			}
    		}
    		return rStr;
    	}catch(Exception e){
    		e.printStackTrace();
    		return e.getMessage();
    	}
    }
    /**
     * 会员新增
     * 针对是否有现金购买卡的会员
     * 如果有则记录到充值消费记录中
     * 对于新增时
     * 充值消费记录将生成两条记录
     *  一条为充值记录
     *  一条为卡成本
     *  @param reChargePrice 充值
     *  @param 收费  卡扣
     * ***/
   public void addMember(Member member ,int reChargePrice,int chargePrice,String chargeType){
	   memberDao.insert(member);
	    if(reChargePrice!=0){
		   Memberchargehistrory hi =new Memberchargehistrory();
		   hi.setMember(member);
		   hi.setChargeTime(new Date());
		   hi.setOptype(ChargeOpType.OnCharge.name());
		   hi.setChargetype(chargeType);
		   hi.setPrice(reChargePrice);
		   hi.setRemark("卡充值"+Utils.toPrice(reChargePrice));
		   memberDao.insert(hi);
	    }
	    if(chargePrice!=0){
		   Memberchargehistrory hi1 =new Memberchargehistrory();
		   hi1.setMember(member);
		   hi1.setChargeTime(new Date());
		   hi1.setOptype(ChargeOpType.OnConsume.name());
		   hi1.setChargetype(chargeType);
		   hi1.setPrice(-chargePrice);
		   hi1.setRemark("购卡"+Utils.toPrice(chargePrice));
		   memberDao.insert(hi1);
		   int balance=this.queryMemberBalance(member);
		   member.setBalance(balance);
		   memberDao.update(member);
	    }
		   if(Hotel.onDuty()){
			   if(reChargePrice!=0)
			      Hotel.receive(reChargePrice, ChargeOpType.OnCharge, PayMethod.CASH);
			   if(chargePrice!=0)
			      Hotel.receive(chargePrice, ChargeOpType.OnConsume, PayMethod.CASH);
		   }
	   
   }
   /**
    * 修改会员时可作同时充值
    * **/
   public void updateMember(Member member,int chargePrice,String chargeType){
	   if(chargePrice!=0){
		   Memberchargehistrory hi =new Memberchargehistrory();
		   hi.setMember(member);
		   hi.setChargeTime(new Date());
		   hi.setOptype(ChargeOpType.OnCharge.name());
		   hi.setChargetype(chargeType);
		   hi.setPrice(chargePrice);
		   hi.setRemark("卡充值"+Utils.toPrice(chargePrice));
		   memberDao.insert(hi);
		   int balance=this.queryMemberBalance(member);
		   member.setBalance(balance);
		   if(Hotel.onDuty()){
			   Hotel.receive(chargePrice, ChargeOpType.OnCharge, PayMethod.CASH);
		   }
	   }
	   memberDao.update(member);
	  
   }
   /***
    * 会员充值、消费、升级等
    * 同时更新会员余额
    * 更新值班人的金额
    * **/
   public Member chargeMember(Memberchargehistrory ms){
	   if(ms!=null){
		   memberDao.insert(ms);
		   Member member =ms.getMember();
		   int balance =queryMemberBalance(member);
		   member.setBalance(balance);
		   memberDao.update(member);
		   if(Hotel.onDuty()){
			   Hotel.receive(ms.getPrice(), ChargeOpType.OnCharge, PayMethod.valueOf(ms.getChargetype()));
		   }
		   return member;
	   }else{
		   return null;
	   }
		   
   }
   /**
    * 通过购买升级会员等级
    * ***/
   public Member buyUpLevel(Member member ,Memberchargehistrory rechargems){
	   /*if(cardms!=null){
		   memberDao.insert(cardms);
	   }*/
	   if(rechargems!=null){
		   memberDao.insert(rechargems);
		   if(Hotel.onDuty()){
			   Hotel.receive(rechargems.getPrice(),ChargeOpType.OnCharge, PayMethod.valueOf(rechargems.getChargetype()));
		   }
	   }
	   int balance =queryMemberBalance(member);
	   member.setBalance(balance);
	   memberDao.update(member);
	   return member;
   }
  /**
   * 通过积分来升级会员等级
   * **/
   public Member integralUpLevel(Member member,IntegralLog log){
	   if(log!=null){
		   memberDao.insert(log);
	   }
	   int b=calMemberBalanceIntegral(member);
	   member.setIntegral(b);
	   memberDao.update(member);
	   return member;
   }
   /**
    * 计算当前会员余额
    * ***/
   public int queryMemberBalance(Member member){
	   
	   return memberDao.queryMemberBalance(member);
   }
   /**
    * 计算当前者会员积分
    * **/
   public int calMemberBalanceIntegral(Member member){
	   StringBuffer hql = new StringBuffer();
	   int i=0;
	   hql.append(" select sum(integral) from IntegralLog b where b.member.id='"+member.getId()+"'");
	   memberDao.find(hql.toString());
	   List o= memberDao.find(hql.toString());
  	   if(o!=null&&o.size()!=0){
  		  Object s= o.get(0);
  		  if(s!=null)
  		   i=Integer.valueOf(s.toString());
  	   }
  	   return i;
   }
   /**查询会员充值消费历史记录
    * 
    * **/
   public List<Memberchargehistrory> queryHistory(Member member){
	   StringBuffer hql = new StringBuffer();
     	hql.append(" from Memberchargehistrory b where b.member.id='"+member.getId()+"' order by b.chargeTime desc");
     	List <Memberchargehistrory> l=memberDao.find(hql.toString());
     	return l;
   }
   /**
    * 查询会员积分记录
    * **/
   public List<IntegralLog> queryIntegral(Member member){
	   StringBuffer hql = new StringBuffer();
    	hql.append(" from IntegralLog b where b.member.id='"+member.getId()+"' order by b.time desc");
    	List <IntegralLog> l=memberDao.find(hql.toString());
    	return l;
   }
   /**
    * 判断当前会员是否与比较会员等级高
    * @param member 当前会员
    * @param memberLevel 会员等级
    * 返回 true 
    *     false
    * 目前是根据会员等级所需的金额高低来判断等级高低
    * ***/
   public boolean isLevelUp(Member member,MemberLevel memberLevel){
	   if(member ==null||memberLevel==null){
		   return false;
	   }
	   if(member.getMemberLevel()==null){
		   return false;
	   }
	   if(member.getMemberLevel().getLevelPrice()>=memberLevel.getLevelPrice()){
		   return false;
	   }
	   return true;
   }
   /**
    * 根据卡号查询会员
    * ***/
   public Member queryMemberOnCard(String card)
   {
	   StringBuffer hql = new StringBuffer();
	   hql.append(" from Member b where b.cardNo='").append(card).append("'");
	   hql.append(" and b.state='").append(MemberState.OnUsed.name()).append("'");
	   List <Member> mList =this.find(hql.toString());
	   if(mList!=null&&mList.size()==1)
	   {
		   return (Member)mList.get(0);
	   }
	   else
		   return null;
   }
   public int countMemberHistoryUsed(Member m,boolean isPositive)
   {
	   return memberDao.countMemberHistoryUsed(m, isPositive);
   }
   public Member queryMemberOnCard(String name,String cardNo){

	  return  memberDao.queryMember(name, cardNo, null, null, null);
   }
   /**
    * 根据会员查找系统对应的卡序列号
    * */
   public String queryCardSerial(Member m){
	   StringBuffer hql = new StringBuffer();
	   hql.append(" from Card b where cardNumber='").append(m.getCardNo()).append("'");
	   List <Card> cList = this.find(hql.toString());
	   if(cList!=null&&cList.size()==1)
	   {
		  Card c=cList.get(0);
		  return c!=null?c.getSerialNumber():null;
	   }
	   else
		   return null;
   }
   public String queryCardState(Member m){
	   StringBuffer hql = new StringBuffer();
	   hql.append(" from Card b where cardNumber='").append(m.getCardNo()).append("'");
	   List <Card> cList = this.find(hql.toString());
	   if(cList!=null&&cList.size()==1)
	   {
		  Card c=cList.get(0);
		  return c!=null?c.getEnable2():"";
	   }
	   else
		   return "未配卡";
   }
   public String queryCardNoBySerial(String serial)
   {
	   StringBuffer hql = new StringBuffer();
	   hql.append(" from Card b where serialNumber='").append(serial).append("'");
	   List <Card> cList = this.find(hql.toString());
	   if(cList!=null&&cList.size()==1)
	   {
		  Card c=cList.get(0);
		  return c!=null?c.getCardNumber():null;
	   }
	   else
		   return null;
   }
   /**
    * 为读卡器服务
    * **/
   public String queryCardExpireTime(String serial){
	   StringBuffer hql = new StringBuffer();
	   hql.append(" from Card b where serialNumber='").append(serial).append("'");
	   List <Card> cList = this.find(hql.toString());
	   if(cList!=null&&cList.size()==1)
	   {
		  Card c=cList.get(0);
		  return c!=null?c.getExpireTime4():null;
	   }
	   else
		   return null;
   }
  /**当前会员金额超过多少
   * @param member
   * @param money 比较金额
   * @param isOverdraft 是否将透支的计算在内
   * 
   * */
   public int exceedBalance(Member member,int money,boolean isOverdraft)
   {
	   if(member==null)
		   return -1;
	   int b =member.getBalance();
	   int overdraft =member.getMemberLevel().getOverdraft();
	   if(isOverdraft){
		   int l =(b+overdraft)-money;
		   return l; 
	   }else
	   {
		   int l =b-money;
		   return l;
	   }
   }
}

